import { Handlers } from "$fresh/server.ts";
import { FreshContext } from "$fresh/src/server/deps.ts"; // For session types, adjust if your Fresh version differs
import { setCookie } from "$std/http/cookie.ts";
import * as bcrypt from "https://deno.land/x/bcrypt@v0.4.1/mod.ts";
import { setAdminSessionCookie, verifyAdminCredentials } from "../../../utils/auth.ts";
import { getDbClient } from "../../../utils/db.ts";

// Helper function to set a session cookie (simplified)
// In a real app, use Fresh's built-in session management or a more robust library
async function createAdminSession(ctx: FreshContext, username: string, nickname: string) {
  const sessionId = crypto.randomUUID(); // Simple session ID
  // Store session in a more persistent way if needed (e.g., Deno KV, Redis)
  // For this example, we'll assume a simple cookie-based session for isAdmin checks
  // NOTE: Real session management is more complex and involves proper state handling.

  const headers = new Headers(ctx.res.headers);
  setCookie(headers, {
    name: "admin_session",
    value: JSON.stringify({ loggedIn: true, username, nickname, sessionId }),
    path: "/",
    httpOnly: true,
    secure: ctx.req.url.startsWith("https:"), // Use secure cookies in production
    sameSite: "Lax",
    maxAge: 60 * 60 * 24 * 7, // 1 week
  });
  return headers;
}

export const handler: Handlers = {
  async POST(req, ctx) {
    const form = await req.formData();
    const username = form.get("username") as string;
    const password = form.get("password") as string;
    const redirectFromForm = form.get("redirect_url") as string | null;
    
    const url = new URL(req.url);
    const redirectFromQuery = url.searchParams.get("redirect");
    let finalRedirectUrl = redirectFromForm || redirectFromQuery || "/";

    // 确保重定向URL安全（只允许相对URL）
    if (finalRedirectUrl.startsWith("http")) {
      finalRedirectUrl = "/";
    }
    
    console.log("登录尝试:", { username, redirectUrl: finalRedirectUrl });

    if (!username || !password) {
      // 重定向回登录，并附带错误信息
      const loginUrl = new URL("/admin/login", url.origin);
      loginUrl.searchParams.set("error", "用户名和密码必填。");
      console.log("错误-缺少凭据，重定向到:", loginUrl.toString());
      return Response.redirect(loginUrl.toString(), 303);
    }

    try {
      // 使用新的验证逻辑
      console.log("开始验证用户凭据:", username);
      const authResult = await verifyAdminCredentials(username, password);
      console.log("验证结果:", JSON.stringify({
        success: authResult.success,
        errorType: authResult.errorType,
        userId: authResult.userId
      }));

      if (!authResult.success) {
        const loginUrl = new URL("/admin/login", url.origin);
        
        // 根据错误类型返回具体的错误信息
        console.log("登录失败，错误类型:", authResult.errorType);
        switch(authResult.errorType) {
          case 'username_not_found':
            loginUrl.searchParams.set("error", "用户名不存在。");
            break;
          case 'incorrect_password':
            loginUrl.searchParams.set("error", "密码错误，请重新输入。");
            break;
          case 'empty_fields':
            loginUrl.searchParams.set("error", "用户名和密码必填。");
            break;
          case 'db_error':
            loginUrl.searchParams.set("error", "数据库错误，请稍后再试。");
            break;
          default:
            loginUrl.searchParams.set("error", "登录失败，请检查用户名和密码。");
        }
        
        console.log("重定向到:", loginUrl.toString());
        return Response.redirect(loginUrl.toString(), 303);
      }

      // 认证成功，创建会话并重定向
      console.log("认证成功，准备设置会话cookie");
      const headers = new Headers();
      await setAdminSessionCookie(
        headers, 
        authResult.userId!, 
        authResult.username!, 
        authResult.displayName!,
        authResult.avatarUrl!
      );
      console.log("会话cookie已设置");

      // 处理重定向
      if (finalRedirectUrl.startsWith("/admin/login")) {
        finalRedirectUrl = "/";
      }
      
      const successRedirectUrl = new URL(finalRedirectUrl, url.origin);
      successRedirectUrl.searchParams.set("login_success", "true");
      
      headers.set("Location", successRedirectUrl.toString());
      console.log("登录成功，重定向到:", successRedirectUrl.toString());

      return new Response(null, {
        status: 303, // See Other
        headers: headers,
      });

    } catch (error) {
      console.error("登录API错误:", error);
      const loginUrl = new URL("/admin/login", url.origin);
      loginUrl.searchParams.set("error", "发生未预期的错误，请重试。");
      console.log("发生错误，重定向到:", loginUrl.toString());
      return Response.redirect(loginUrl.toString(), 303);
    }
  },
}; 